package control

import (
	"github.com/gin-gonic/gin"
	"myself/constants"
	"myself/db/models"
	"myself/logic"
	"myself/rsp"
)

type postingIn struct {
	Id      *uint32 `json:"id"`
	Title   *string `json:"title"`
	Content *string `json:"content"`
}

func CreatePosting(context *gin.Context) {
	json := &postingIn{}
	context.BindJSON(json)
	accountId, _ := context.Get("account_id")

	postingLogin := logic.NewPostingLogic()
	modelInfo, err := postingLogin.CreatePosting(*json.Title, *json.Content, accountId.(string))
	if err != nil {
		rsp.FailResponse(context, err.Error(), constants.FailCode)
		return
	}
	rsp.SuccessResponse(context, modelInfo)
}

func UpdatePosting(context *gin.Context) {
	json := &postingIn{}
	context.BindJSON(json)
	accountId, _ := context.Get("account_id")

	postingLogin := logic.NewPostingLogic()
	effect, err := postingLogin.UpdatePosting(*json.Id, json.Title, json.Content, accountId.(string))
	if err != nil {
		rsp.FailResponse(context, err.Error(), constants.FailCode)
		return
	}
	rsp.SuccessResponse(context, map[string]int64{"effect": effect})
}

func GetAllPosting(context *gin.Context) {
	postingLogin := logic.NewPostingLogic()
	postingList, err := postingLogin.SelectAllPosting(nil, nil, nil, nil)
	if err != nil {
		rsp.FailResponse(context, err.Error(), constants.FailCode)
		return
	}
	rsp.SuccessResponse(context, map[string][]models.Posting{"posting_list": postingList})
}

type postingCondition struct {
	Id        *uint32 `json:"id"`
	Title     *string `json:"title"`
	Content   *string `json:"content"`
	AccountId *string `json:"account_id"`
}

func GetAllPostingByCondition(context *gin.Context) {
	json := &postingCondition{}
	context.BindJSON(&json)
	postingLogin := logic.NewPostingLogic()
	postingList, err := postingLogin.SelectAllPosting(json.Id, json.Title, json.Content, json.AccountId)
	if err != nil {
		rsp.FailResponse(context, err.Error(), constants.FailCode)
		return
	}
	rsp.SuccessResponse(context, map[string][]models.Posting{"posting_list": postingList})
}
